package user.servlet;

import com.alibaba.fastjson.JSONObject;
import user.entity.Administrator;
import user.service.AdministratorService;
import user.service.impl.AdministratorServiceImpl;

import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;

import dao.JedisUtils;



@WebServlet("/LoginServlet")
public class LoginServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String account = request.getParameter("username");
        String pwd = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");

        AdministratorService service =new AdministratorServiceImpl();
        Administrator userEntity=service.Login(account,pwd);
        PrintWriter out = response.getWriter();
        JSONObject jsonObject = new JSONObject();

        if(userEntity==null){//账号密码错误
            jsonObject.put("state","0");

        }else{
            if("true".equals(rememberMe)){
                //随机数
                String tokenStr = String.valueOf((int) ((Math.random()*9+1)*1000));

                JedisUtils.setString(tokenStr, JSONObject.toJSONString(userEntity));
//                HttpSession session =request.getSession();
//                Cookie cookie = new Cookie("userToken",tokenStr);
//                response.addCookie(cookie);
                jsonObject.put("tokenStr",tokenStr);
            }
            jsonObject.put("state","1");
        }
        out.print(jsonObject.toString());
    }
}
